package 文件;

import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;
import java.io.File;

public class FileBrowser extends JFrame{
    private JTree tree;
    public FileBrowser(){
        setTitle("我的资源管理器");
        setVisible(true);
        setSize(300,600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocation(600,200);
        DefaultMutableTreeNode root=new DefaultMutableTreeNode("我的电脑");
        tree=new JTree(root);
        tree.addTreeWillExpandListener(new TreeWillExpandListener() {
            @Override
            public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
                TreePath tp = event.getPath();
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent();
                Object o = node.getUserObject();
                File file;
                if (o instanceof File) {
                    file = (File) o;
                    File[] fs = file.listFiles();
                    if (fs!=null)
                        for (File f : fs) {
                            DefaultMutableTreeNode n = new DefaultMutableTreeNode(f);
                            if (f.isDirectory()) {
                                DefaultMutableTreeNode cur = new DefaultMutableTreeNode(".");
                                DefaultMutableTreeNode pre = new DefaultMutableTreeNode("..");
                                n.add(cur);
                                n.add(pre);
                            }
                            node.add(n);
                        }
                }
            }

            @Override
            public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {

            }
        });
        JScrollPane sp=new JScrollPane(tree);
        add(sp);
        File[]fs=File.listRoots();

        for (File file:fs){
            DefaultMutableTreeNode node=new DefaultMutableTreeNode(file);
            if (file.isDirectory()){
                DefaultMutableTreeNode cur=new DefaultMutableTreeNode(".");
                DefaultMutableTreeNode pre=new DefaultMutableTreeNode("..");
                node.add(cur);
                node.add(pre);
            }
            root.add(node);
        }
    }
    public static void main(String[]args){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FileBrowser();
            }
        });
    }
}
